/**
 * 
 */
package com.teleca.jamendo.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;

import com.teleca.jamendo.R;
import com.teleca.jamendo.dialog.TutorialDialog;
import com.teleca.jamendo.ui.BaseActivity;

/**
 * 启动加载页面
 * 
 * @author Marcin Gil
 * 
 */
public class SplashscreenActivity extends BaseActivity {
	public final static String FIRST_RUN_PREFERENCE = "first_run";

	private Animation endAnimation;

	private Handler endAnimationHandler;
	private Runnable endAnimationRunnable;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.splashscreen);

		endAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
		endAnimation.setFillAfter(true);

		endAnimationHandler = new Handler();
		endAnimationRunnable = new Runnable() {
			@Override
			public void run() {
				findViewById(R.id.splashlayout).startAnimation(endAnimation);
			}
		};

		endAnimation.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				Intent intent = new Intent(SplashscreenActivity.this, HomeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				SplashscreenActivity.this.startActivity(intent);
				SplashscreenActivity.this.finish();
			}
		});

		showTutorial();
	}

	final void showTutorial() {
		boolean showTutorial = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(FIRST_RUN_PREFERENCE,
				true);
		if (showTutorial) {
			final TutorialDialog dlg = new TutorialDialog(this);
			dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
				@Override
				public void onDismiss(DialogInterface dialog) {
					CheckBox cb = (CheckBox) dlg.findViewById(R.id.toggleFirstRun);
					if (cb != null && cb.isChecked()) {
						SharedPreferences prefs = PreferenceManager
								.getDefaultSharedPreferences(SplashscreenActivity.this);
						prefs.edit().putBoolean(FIRST_RUN_PREFERENCE, false).commit();
					}
					endAnimationHandler.removeCallbacks(endAnimationRunnable);
					endAnimationHandler.postDelayed(endAnimationRunnable, 2000);
				}
			});
			dlg.show();

		} else {
			endAnimationHandler.removeCallbacks(endAnimationRunnable);
			endAnimationHandler.postDelayed(endAnimationRunnable, 1500);
		}
	}
}
